﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.SystemUI;
using System.Configuration;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using System.Runtime.InteropServices;
using WindowsApplication1.dialog;
using System.Data.Common;
using System.IO;
using ESRI.ArcGIS.esriSystem;
using System.Diagnostics;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesGDB;
using System.Collections;
using mapSpliter;
using pnmodel;
using com.zjgis.arcengineutility;
using com.zjgis.control;
using Oracle.DataAccess.Client;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.ConversionTools;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public static IFeatureLayer 建筑图层;
        public static IFeatureLayer 社区图层;
        public static IFeatureLayer 街道图层;
        public static IFeatureLayer 用电建筑图层;
        public static IFeatureLayer 单元数检查;
        public static ILayer 道路;
        public Form1()
        {
            DbConnection conn = CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
            try
            {
                conn.Open();
                DbCommand command = conn.CreateCommand();
                command.CommandText = "update sde.layers t set srid = (select srid from sde.layers where owner = t.owner and table_name = '" + Settings.建筑图层 + "') where table_name = '" + Settings.用电建筑图层 + "'";
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库连接失败！\n原因：" + ex.Message);
                this.Close();
                return;
            }
            finally
            {
                conn.Close();
            }
            InitializeComponent();
            QueryResultPanel.Instance.Dock = DockStyle.Left;
            QueryResultPanel.Instance.Visible = false;
            toolStripContainer1.ContentPanel.Controls.Add(QueryResultPanel.Instance);
            this.toolStrip4.Visible = false;
            this.Text = "杭州用电建筑管理系统[数据处理版]";
            axMapControl1.LoadMxFile(Application.StartupPath + "\\" + ConfigurationManager.AppSettings["图层路径"]);
            for (int i = 0; i < axMapControl1.LayerCount; i++)
            {
                ILayer layer = axMapControl1.get_Layer(i);
                if (layer.Name == ConfigurationManager.AppSettings["街道图层"])
                {
                    街道图层 = (layer as IFeatureLayer);
                }
                else if (layer.Name == ConfigurationManager.AppSettings["社区图层"])
                {
                    社区图层 = layer as IFeatureLayer;
                }
                else if (layer.Name == ConfigurationManager.AppSettings["建筑图层"])
                {
                    建筑图层 = (layer as IFeatureLayer);
                }
                else if (layer.Name == ConfigurationManager.AppSettings["用电建筑图层"])
                {
                    用电建筑图层 = layer as IFeatureLayer;
                }
                else if (layer.Name == "建筑单元数检查")
                {
                    单元数检查 = layer as IFeatureLayer;
                }
                else if (layer.Name == "道路")
                {
                    道路 = layer;
                }
            }
        }
        public Form1(string admin)
            : this()
        {
            if (admin == "admin")
            {
                this.Text = "杭州用电建筑管理系统[管理员版]";
                this.toolStrip1.Visible = false;
                this.toolStrip2.Visible = false;
                this.toolStrip3.Visible = false;
                this.toolStrip4.Visible = true;
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            clicktoolstrip(toolStrip1, axToolbarControl1, sender as ToolStripItem);
        }
        private void clicktoolstrip(ToolStrip strip, AxToolbarControl control, ToolStripItem button)
        {
            int index = strip.Items.IndexOf(button);
            IToolbarItem toolbarItem = control.GetItem(index);
            if (toolbarItem != null)
            {
                ICommand command = toolbarItem.Command;
                command.OnClick();
                if (command is ITool)
                    axMapControl1.CurrentTool = command as ITool;
            }
        }
        private void printButton6_Click(object sender, EventArgs e)
        {
            if (shequComboBox1.SelectedItem == null)
            {
                MessageBox.Show("您没有选择要打印的社区!");
                return;
            }
            NameAndGeometry ne = shequComboBox1.SelectedItem as NameAndGeometry;
            IGeometry geometry = ne.Geometry;
            IEnvelope env = geometry.Envelope;

            double a3width = 29.7 / 2.54 * 96;
            double a3height = 42 / 2.54 * 96;

            mapSpliter.MapSpliter mapspliter = new MapSpliter();
            mapspliter.setActiveView(axMapControl1.ActiveView);
            mapspliter.setGeometry(ne.Geometry);
            string outputPath = "c:\\" + ne.ToString();
            if (!Directory.Exists(outputPath))
                Directory.CreateDirectory(outputPath);
            mapspliter.setOutput(outputPath);
            mapspliter.setPicSize((int)a3width, (int)a3height);
            mapspliter.setStartPoint(env.XMin, env.YMax);
            mapspliter.setOverlapRatio(double.Parse(ConfigurationManager.AppSettings["交叠度"]));
            double[] scales = new double[] { axMapControl1.MapScale };
            mapspliter.splitMap(scales, env.XMin, env.YMin, env.XMax, env.YMax);
            MessageBox.Show("打印成功");
            Process.Start("explorer.exe", outputPath);
        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            Identify iden = new Identify();
            iden.OnCreate(axMapControl1.GetOcx());
            axMapControl1.CurrentTool = iden;
            iden.ShowForm();
        }
        ToolStripButton checkedbutton = null;
        private void toolStripButton12_CheckedChanged(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            if (tsb.Checked)
            {
                if (tsb == checkedbutton)
                    return;
                ToolStripButton cb = checkedbutton;
                checkedbutton = tsb;
                if (cb != null)
                    cb.Checked = false;
            }
            else if (tsb == checkedbutton)
            {
                tsb.Checked = true;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Dispose();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            toolStripStatusLabel1.Text = "当前坐标:" + e.mapX.ToString().PadRight(20, ' ').Substring(0, 8) + "米 , " + e.mapY.ToString().PadRight(20, ' ').Substring(0, 8) + "米";
        }
        /// <summary>
        /// 给建筑编号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            string shequbianhao = Settings.社区编号;
            string buildid = Settings.建筑编号;
            int bdid = 建筑图层.FeatureClass.FindField(buildid);
            int shequid = 社区图层.FeatureClass.FindField(shequbianhao);
            ISpatialFilter qfilter = new SpatialFilterClass();
            IFeatureCursor fcursor = 社区图层.Search(null, true);

            IFeature shequFeature = fcursor.NextFeature();
            DbConnection conn = CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
            conn.Open();
            DbCommand comm = conn.CreateCommand();
            while (shequFeature != null)
            {
                ISpatialFilter spfilterb = new SpatialFilterClass();
                spfilterb.WhereClause = "trim(" + buildid + ") is null";
                spfilterb.Geometry = shequFeature.Shape;
                spfilterb.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                spfilterb.GeometryField = 建筑图层.FeatureClass.ShapeFieldName;
                IFeatureCursor buildfcursor = 建筑图层.FeatureClass.Update(spfilterb, true);

                IFeature bdfeature = buildfcursor.NextFeature();
                string shequhao = shequFeature.get_Value(shequid).ToString();
                comm.CommandText = "select max(to_number(buildingid)) from 建筑 where instr(buildingid,'" + shequhao + "') = 1";
                object obj = comm.ExecuteScalar();
                int id = 10001;
                if (!(obj is System.DBNull))
                {
                    id = int.Parse(obj.ToString().Replace(shequhao, "")) + 1;
                }
                while (bdfeature != null)
                {
                    bdfeature.set_Value(bdid, shequhao + id.ToString());
                    id++;
                    buildfcursor.UpdateFeature(bdfeature);
                    bdfeature = buildfcursor.NextFeature();
                }
                //buildfcursor.Flush();
                Marshal.ReleaseComObject(buildfcursor);
                shequFeature = fcursor.NextFeature();
            }

            Marshal.ReleaseComObject(fcursor);
            conn.Close();
        }
        /// <summary>
        /// 按关键字查询建筑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            string text = this.toolStripTextBox1.Text;

            string sql = "select (select a.shape.get_gtype() as shape from 建筑 a where a.buildingid = t.建筑统一编码) as shapetype,(select a.shape.Get_WKT() as shape from 建筑 a where a.buildingid = t.建筑统一编码) as shape, t.* from 用电建筑信息 t where t.建筑统一编码 like '%" + text + "%'or t.手工编码 like '%" + text + "%' or t.建筑地址 like '%" + text + "%' or t.建筑名称 like '%" + text + "%' or t.楼幢号 like '%" + text + "%'";
            QueryResultPanel form2 = QueryResultPanel.Instance;
            form2.ShowQueryResult(sql, axMapControl1.GetOcx() as IMapControl2);
            form2.treeView1.ExpandAll();
            form2.SetVisible();
        }

        public static DbConnection CreateDbConnection(string providerName, string connectionString)
        {
            // Assume failure.
            DbConnection connection = null;

            // Create the DbProviderFactory and DbConnection.
            if (connectionString != null)
            {
                try
                {
                    DbProviderFactory factory =
                        DbProviderFactories.GetFactory(providerName);

                    connection = factory.CreateConnection();
                    connection.ConnectionString = connectionString;
                }
                catch (Exception ex)
                {
                    // Set the connection to null if it was created.
                    if (connection != null)
                    {
                        connection = null;
                    }
                    File.AppendAllText("log.txt", ex.Message);
                    File.AppendAllText("log.txt", ex.StackTrace);
                }
            }
            // Return the connection.
            return connection;
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            IToolbarItem toolbarItem = axToolbarControl2.GetItem(0);
            if (toolbarItem != null)
            {
                ICommand command = toolbarItem.Command;
                command.OnClick();
                if (command is ITool)
                    axMapControl1.CurrentTool = command as ITool;
            }
        }

        private void toolStripButton14_Click(object sender, EventArgs e)
        {
            IToolbarItem toolbarItem = axToolbarControl2.GetItem(1);
            if (toolbarItem != null)
            {
                ICommand command = toolbarItem.Command;
                command.OnClick();
                if (command is ITool)
                    axMapControl1.CurrentTool = command as ITool;
            }
        }
        /// <summary>
        /// 建筑合并
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton9_Click(object sender, EventArgs e)
        {

            IFeatureClass dianfc = 用电建筑图层.FeatureClass;
            IGeoDatasetSchemaEdit schemaEdit = dianfc as IGeoDatasetSchemaEdit;
            schemaEdit.AlterSpatialReference(((IGeoDataset)建筑图层.FeatureClass).SpatialReference);
            
            IFeatureSelection fs = 建筑图层 as IFeatureSelection;
            ISelectionSet ss = fs.SelectionSet;
            if (ss.Count == 0)
            {
                MessageBox.Show("没有选中任何建筑");
                return;
            }
            IEnumIDs ids = ss.IDs;
            int idsvalue = ids.Next();
            int[] idarray = new int[ss.Count];
            int i = 0;
            while (idsvalue != -1)
            {
                idarray[i] = idsvalue;
                i++;
                idsvalue = ids.Next();
            }
            IFeatureClass fclass = 建筑图层.FeatureClass;
            IGeoDatabaseBridge bridge = new GeoDatabaseHelperClass() as IGeoDatabaseBridge;
            IFeatureCursor fcursor = bridge.GetFeatures(fclass, ref idarray, false);
            IFeature feature = fcursor.NextFeature();

            double buildingarea = 0;//area * floor
            double coverarea = 0;
            int maxfloor = 0;
            string buildid = null;
            int floorindex = fclass.Fields.FindField("FLOOR");
            int indexid = fclass.FindField(Settings.建筑编号);
            int hasdataindex = fclass.FindField("hasdata");
            int codeindex = fclass.FindField(Settings.用电建筑编号);
            ITopologicalOperator polygon = new PolygonClass() as ITopologicalOperator;
            IGeometryCollection geocoll = new GeometryBagClass();
            string ebuildid = null;
            while (feature != null)
            {
                if (feature.get_Value(hasdataindex) != null && feature.get_Value(hasdataindex).ToString() == "1")
                {
                    if (buildid != null)
                    {
                        MessageBox.Show("选中了两个有数据的建筑，合并失败！");
                        Marshal.ReleaseComObject(fcursor);
                        return;
                    }
                    else
                    {
                        buildid = feature.get_Value(indexid).ToString();
                    }
                }
                object obj21 = feature.get_Value(feature.Fields.FindField(Settings.用电建筑编号));
                if (obj21 != null && obj21.ToString() != "")
                {
                    if (ebuildid != null)
                    {
                        if (obj21.ToString() != ebuildid)
                        {
                            MessageBox.Show("选中的建筑中包含已经被合并的建筑！");
                            Marshal.ReleaseComObject(fcursor);
                            return;
                        }
                    }
                    else
                    {
                        ebuildid = obj21.ToString();
                    }
                }
                int floor = 1;
                try
                {
                    floor = int.Parse(feature.get_Value(floorindex).ToString());
                    if (floor > maxfloor)
                        maxfloor = floor;
                }
                catch { }
                IGeometry geom = feature.Shape;
                object obj = Type.Missing;
                if (!geom.IsEmpty)
                {
                    IArea iarea = geom as IArea;
                    buildingarea += iarea.Area * floor;
                    coverarea += iarea.Area;
                    geocoll.AddGeometry(geom, ref obj, ref obj);
                }
                feature = fcursor.NextFeature();
            }
            if (buildid == null)
            {
                MessageBox.Show("没有选中有数据的建筑，合并失败！");
                Marshal.ReleaseComObject(fcursor);
                return;
            }
            string communityid = buildid.Substring(0, 12);
            Marshal.ReleaseComObject(fcursor);
            polygon.ConstructUnion(geocoll as IEnumGeometry);

            polygon.Simplify();
            polygon = polygon.ConvexHull() as ITopologicalOperator;

            IQueryFilter filter = new QueryFilterClass();
            string cqbm = ConfigurationManager.AppSettings["区编号"];
            string cqm = ConfigurationManager.AppSettings["区名称"];
            string cid = ConfigurationManager.AppSettings["社区编号"];
            string cname = ConfigurationManager.AppSettings["社区名称"];
            string sname = ConfigurationManager.AppSettings["街道名称"];
            string sid = ConfigurationManager.AppSettings["街道编号"];
            filter.WhereClause = cid + "= '" + communityid + "'";
            IFeatureCursor fcursor1 = 社区图层.Search(filter, true);
            feature = fcursor1.NextFeature();
            if (feature == null)
            {
                MessageBox.Show("未找到编号为" + communityid + "的社区,建筑合并不能进行");
                Marshal.ReleaseComObject(fcursor);
                Marshal.ReleaseComObject(fcursor1);
                return;
            }
            else
            {
                IFeatureClass updateFC = 用电建筑图层.FeatureClass;
                IQueryFilter2 queryfilter = new QueryFilterClass() as IQueryFilter2;
                queryfilter.SubFields = "*";
                queryfilter.WhereClause = Settings.用电建筑编号 + "='" + buildid + "'";
                IFeatureCursor fcursor2 = updateFC.Update(queryfilter, false);
                IFeature feature2 = fcursor2.NextFeature();
                string cqbmvalue = feature.get_Value(社区图层.FeatureClass.FindField(cqbm)).ToString();
                    string cqmvalue = feature.get_Value(社区图层.FeatureClass.FindField(cqm)).ToString();
                    string cnamevalue = feature.get_Value(社区图层.FeatureClass.FindField(cname)).ToString();
                    string sidvalue = feature.get_Value(社区图层.FeatureClass.FindField(sid)).ToString();
                    string snamevalue = feature.get_Value(社区图层.FeatureClass.FindField(sname)).ToString();
                    IEnvelope reflectEnv = polygon.Boundary.Envelope;
                if (feature2 == null)
                {
                    Marshal.ReleaseComObject(fcursor2);
                    fcursor2 = updateFC.Insert(true);
                    IFeatureBuffer fbuffer = updateFC.CreateFeatureBuffer();
                    fbuffer.set_Value(updateFC.FindField("城区编码"), cqbmvalue);
                    fbuffer.set_Value(updateFC.FindField("城区名称"), cqmvalue);
                    fbuffer.set_Value(updateFC.FindField("社区名"), cnamevalue);
                    fbuffer.set_Value(updateFC.FindField("街道编码"), sidvalue);
                    fbuffer.set_Value(updateFC.FindField("街道名"), snamevalue);
                    fbuffer.set_Value(updateFC.FindField("社区编码"), communityid);
                    fbuffer.set_Value(updateFC.FindField(Settings.用电建筑编号), buildid);
                    fbuffer.set_Value(updateFC.FindField("建筑层数"), maxfloor);
                    fbuffer.set_Value(updateFC.FindField("建筑面积"), buildingarea);
                    fbuffer.set_Value(updateFC.FindField("建筑投影面积"), coverarea);
                    fbuffer.Shape = polygon as IGeometry;
                    reflectEnv = polygon.Boundary.Envelope;
                    fcursor2.InsertFeature(fbuffer);
                    fcursor2.Flush();
                    Marshal.ReleaseComObject(fcursor2);
                }
                else
                {
                    IFeature fbuffer = feature2;
                    fbuffer.set_Value(updateFC.FindField("城区编码"), cqbmvalue);
                    fbuffer.set_Value(updateFC.FindField("城区名称"), cqmvalue);
                    fbuffer.set_Value(updateFC.FindField("社区名"), cnamevalue);
                    fbuffer.set_Value(updateFC.FindField("街道编码"), sidvalue);
                    fbuffer.set_Value(updateFC.FindField("街道名"), snamevalue);
                    fbuffer.set_Value(updateFC.FindField("社区编码"), communityid);
                    fbuffer.set_Value(updateFC.FindField(Settings.用电建筑编号), buildid);
                    fbuffer.set_Value(updateFC.FindField("建筑层数"), maxfloor);
                    fbuffer.set_Value(updateFC.FindField("建筑面积"), buildingarea);
                    fbuffer.set_Value(updateFC.FindField("建筑投影面积"), coverarea);
                    reflectEnv = fbuffer.Shape.Envelope;
                    reflectEnv.Union(polygon.Boundary.Envelope);
                    fbuffer.Shape = polygon as IGeometry;
                    fbuffer.Store();
                    Marshal.ReleaseComObject(fcursor2);
                }

                DbConnection conn = CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                conn.Open();
                try
                {
                    OracleCommand ocomm = conn.CreateCommand() as OracleCommand;
                    
                    ocomm.CommandText = "update 建筑 set 建筑统一编码 = '' where 建筑统一编码 = '" + buildid + "'";
                    ocomm.ExecuteNonQuery();
                    string idstrs = "";
                    foreach (int ida in idarray)
                    {
                        idstrs += ida + ",";
                    }
                    idstrs = idstrs.Trim(',');
                    ocomm.CommandText = "update 建筑 set 建筑统一编码 = '" + buildid + "' where objectid in (" + idstrs + ")";
                    ocomm.ExecuteNonQuery();
                    reflectEnv.Expand(reflectEnv.Width * 0.1,reflectEnv.Height * 0.1, false);
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground,null,reflectEnv);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally { conn.Close(); }
            }
            Marshal.ReleaseComObject(fcursor1);
            

        }
        /// <summary>
        /// 数据入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton15_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = true;
            ofd.Filter = "csv|*.csv";
            string errorfileDir = Application.StartupPath + "\\错误数据" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff");
            bool allright = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (Directory.Exists(errorfileDir))
                {
                    Directory.Delete(errorfileDir, true);
                }
                string[] filesstr = ofd.FileNames;
                DbConnection conn = CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                conn.Open();
                DbCommand command = conn.CreateCommand();
                command.CommandText = "select registration_id from sde.table_registry t where upper(owner) = '" + ((IDataset)Form1.建筑图层.FeatureClass).Workspace.ConnectionProperties.GetProperty("user").ToString().ToUpper() + "' and upper(table_name) = '" + Settings.用电建筑信息.ToUpper() + "'";
                
                object obj1 = command.ExecuteScalar();
                if (obj1 == null)
                {
                    MessageBox.Show(Settings.用电建筑信息 + "objectid 字段序列有误！");
                    return;
                }
                string sequence = "R" + obj1.ToString();
                int fieldscount = ConfigurationManager.AppSettings["数据字段序列"].Split(',').Length;
                foreach (string file in filesstr)
                {
                    allright = true;
                    try
                    {
                        string shequname = System.IO.Path.GetFileNameWithoutExtension(file);
                        command.CommandText = "select CommunitID from 社区 where Community = '" + shequname + "'";
                        object obj = command.ExecuteScalar();
                        if (obj == null)
                        {
                            allright = false;
                            //输出文件
                            MessageBox.Show("文件名" + shequname + "不符合规定，请修改后重新导入");
                            File.Copy(file, errorfileDir + "\\" + System.IO.Path.GetFileName(file));
                            continue;
                        }
                        string[] alllines = File.ReadAllLines(file, Encoding.Default);
                        if (alllines.Length == 0)
                        {
                            MessageBox.Show("文件" + file + "没有数据");
                        }
                        else
                        {
                            string title = alllines[0];
                            if (title != ConfigurationManager.AppSettings["数据字段序列"])
                            {
                                allright = false;
                                //输出文件
                                MessageBox.Show("文件" + shequname + "字段顺序或名称有问题，请修改后重新导入");
                                if (!Directory.Exists(errorfileDir))
                                {
                                    Directory.CreateDirectory(errorfileDir);
                                }
                                File.Copy(file, errorfileDir + "\\" + System.IO.Path.GetFileName(file));
                                continue;
                            }
                            string errorlines = title;
                            for (int lineindex = 1; lineindex < alllines.Length; lineindex++)
                            {
                                string datastr = alllines[lineindex];

                                bool checkedok = checkdata(datastr, ref allright, ref errorlines,fieldscount);
                                if (!checkedok)
                                {
                                    allright = false;
                                }
                                else
                                {
                                    string[] datas = datastr.Split(',');

                                    datastr = "'" + obj.ToString() + datastr.Replace(",", "','") + "'";
                                    datastr = datastr.Replace(" ", "");
                                    string buildingid = obj.ToString() + datas[0];
                                    try
                                    {
                                        //删除原有数据
                                        string sql = "delete from " + Settings.用电建筑信息 + " where " + Settings.用电建筑编号 + " = '" + buildingid + "'";
                                        command.CommandText = sql;
                                        command.ExecuteNonQuery();
                                        //更新编号为buildingid的建筑，将hasdata属性设置为0
                                        command.CommandText = "update " + Settings.建筑图层 + " set hasdata = 0 where " + Settings.建筑编号 + " = '" + buildingid + "'";
                                        if (command.ExecuteNonQuery() < 1)
                                        {
                                            if (checkedok)
                                                errorlines += "\n" + datastr.Replace("'", "") + "；不存在编号为" + buildingid + "的建筑";

                                            else
                                            {
                                                errorlines += "；不存在编号为" + buildingid + "的建筑";
                                                checkedok = false;
                                            }
                                        }
                                        else
                                        {
                                            string objectidvalue = datastr.Substring(0, datastr.IndexOf(','));
                                            sql = "insert into " + Settings.用电建筑信息 + " (objectid," + title + ") values(" + sequence + ".nextval," + datastr + ")";
                                            command.CommandText = sql;
                                            if (command.ExecuteNonQuery() != 1)
                                            {
                                                if (checkedok)
                                                    errorlines += "\n" + datastr.Replace("'", "").Substring(12) + "；插入数据库失败";
                                                MessageBox.Show("插入失败！");
                                            }
                                            else
                                            {
                                                command.CommandText = "update " + Settings.建筑图层 + " set hasdata = 1 where " + Settings.建筑编号 + " = '" + buildingid + "'";
                                                command.ExecuteNonQuery();
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        //将数据输出
                                        //将数据输出
                                        if (checkedok)
                                            errorlines += "\n" + datastr.Replace("'", "").Substring(12) + "；插入数据失败：" + ex.Message;
                                        else
                                        {
                                            errorlines += "；" + ex.Message;
                                        }
                                        allright = false;
                                    }
                                }
                            }
                            if (!allright && errorlines != title)
                            {
                                if(!Directory.Exists(errorfileDir))
                                {
                                    Directory.CreateDirectory(errorfileDir);
                                }
                                File.AppendAllText(errorfileDir + "\\" + System.IO.Path.GetFileName(file), errorlines, Encoding.Default);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("数据入库失败，原因：" + ex.Message);
                        return;
                    }
                }
                //string sql1 = "update 建筑 set hasdata = 1 where BuildingID in (select 建筑统一编码 from 用电建筑信息)";
                //command.CommandText = sql1;
                //command.ExecuteNonQuery();
                //sql1 = "update 建筑 set hasdata = 0 where BuildingID not in (select 建筑统一编码 from 用电建筑信息)";
                //command.CommandText = sql1;
                //command.ExecuteNonQuery();
                //如果创建了错误文件夹，说明有错误文件存在！
                if (Directory.Exists(errorfileDir))
                {
                    MessageBox.Show("数据已经输入到系统，点击确定后查看错误数据文件");
                    Process.Start("explorer", errorfileDir);
                }
                else
                {
                    MessageBox.Show("数据入库已完成！");
                }
                conn.Close();
            }
        }

        private bool checkdata(string datastr, ref bool allright, ref string errorlines,int fieldscount)
        {
            #region 数据合法性检查
            string error = "";
            string[] datas = datastr.Split(',');
            if (datas.Length == fieldscount)
            {
                if (datas[0] == "" || datas[0].Length != 5)
                {
                    //将数据输出
                    error += "建筑统一编码字段有错误，建筑统一编码应为5位数字；";
                    allright = false;
                    //                                    continue;
                }
                if (datas[2] == "" && datas[3] == "")
                {
                    //将数据输出
                    error += "建筑地址和楼幢号不能同时为空；";
                    allright = false;
                    //                                    continue;
                }
                if (datas[5] != "1" && datas[5] != "2" && datas[5] != "3")
                {
                    //将数据输出
                    //将数据输出
                    error += "建筑类型有错误，该字段必须录入 1、2、3；";
                    allright = false;
                    //                                  continue;
                    
                }
                if (datas[5] == "1" && datas[6] != "0")
                {
                        //将数据输出
                        error += "建筑功能有错误，建筑类型为2或3时必须录入，建筑类型为1时，建筑类型必须为0，建筑类型的取值范围0~10；";
                        allright = false;
                        //                                    continue;
                }
                if (datas[5] == "2" || datas[5] == "3")
                {
                    int btype = -1;

                    if (!int.TryParse(datas[6], out btype) || (btype < 1 || btype > 10))
                    {
                        //将数据输出
                        //将数据输出
                        error += "建筑功能有错误，建筑类型为2或3时必须录入，建筑类型为1时，建筑类型必须为0，建筑类型的取值范围0~10；";
                        allright = false;
                        //                                    continue;

                    }
                }
                {
                    int byear = -1;
                    string jstr = datas[7];
                    for (int charindex = jstr.Length - 1; charindex >= 0; charindex--)
                    {
                        if (jstr[charindex] < '1' || jstr[charindex] > '9')
                            jstr = jstr.Remove(charindex, 1);
                    }
                    if (!int.TryParse(jstr, out byear))
                    {
                        //将数据输出
                        //将数据输出
                        error += "建造年代有错误，该字段必须录入，字段类型是数字；";
                        allright = false;
                        //                                  continue;

                    }
                }
                {
                    int byear = -1;
                    if (!int.TryParse(datas[8], out byear) || (byear < 1 || byear > 4))
                    {
                        //将数据输出
                        //将数据输出
                        error += "建筑结构有错误，必须录入1、2、3、4其中一个；";
                        allright = false;
                        //                                continue;

                    }
                }
                {
                    int byear = -1;

                    if (!int.TryParse(datas[9], out byear) || (byear < 1 || byear > 3))
                    {
                        //将数据输出
                        //将数据输出
                        error += "屋顶形式有错误，必须录入 1、2、3其中一个；";
                        allright = false;
                        //                              continue;

                    }
                }
                {
                    int byear = -1;

                    if (!int.TryParse(datas[10], out  byear) || (byear < 1 || byear > 3))
                    {
                        //将数据输出
                        //将数据输出
                        error += "玻璃幕墙有错误，必须录入 1、2、3其中一个；";
                        allright = false;
                        //                            continue;

                    }
                }
                {
                    int byear = -1;

                    if (!int.TryParse(datas[11], out byear))
                    {
                        //将数据输出
                        //将数据输出
                        error += "电梯数有错误，必须录入数字；";
                        allright = false;
                        //                          continue;

                    }
                }
                {
                    //空调数
                    if (datas[12] != "")
                    {
                        int byear = -1;
                        if (!int.TryParse(datas[12], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "空调数有错误，该字段类型是数字；";
                            allright = false;
                            //                            continue;

                        }
                    }
                }
                {//户数
                    if (datas[5] == "1")
                    {
                        int byear = -1;

                        if (!int.TryParse(datas[13], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "户数有错误，建筑类型为1时必须录入，字段类型是数字；";
                            allright = false;
                            //                          continue;

                        }
                    }
                    else
                    {
                        int byear = -1;

                        if (datas[13] != "" && !int.TryParse(datas[13], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "户数有错误，建筑类型为1时必须录入，字段类型是数字；";
                            allright = false;
                            //                          continue;

                        }
                    }
                }
                {//单元数
                    if (datas[14] != "")
                    {
                        int byear = -1;
                        if (!int.TryParse(datas[14], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "单元数有错误，该字段类型是数字；";
                            allright = false;
                            //                    continue;

                        }
                    }
                }
                {//太阳能利用
                    int byear = -1;
                    if (!int.TryParse(datas[15], out byear))
                    {
                        //将数据输出
                        //将数据输出
                        error += "太阳能利用有错误，必须录入，该字段类型是数字；";
                        allright = false;
                        //                    continue;

                    }
                }
                {//空调类型
                    if (datas[5] == "2" || datas[5] == "3")
                    {
                        int byear = -1; ;
                        if (!int.TryParse(datas[16], out byear) || (byear < 0 || byear > 3))
                        {
                            //将数据输出
                            //将数据输出
                            error += "空调类型有错误，建筑类型为2或3时必须录入0、1、2、3的其中一个；";
                            allright = false;
                            //                      continue;

                        }
                    }
                }
                {//空调系统类型
                    if (datas[5] == "2" || datas[5] == "3")
                    {
                        int byear = -1;
                        int.TryParse(datas[17], out byear);
                        if (byear < 1 || byear > 4)
                        {
                            //将数据输出
                            //将数据输出
                            error += "空调系统类型有错误，建筑类型为2或3时必须录入 1、2、3、4的其中一个；";
                            allright = false;
                            //                    continue;

                        }
                    }
                }
                {//制热量
                    if (datas[19] != "")
                    {
                        int byear = -1;
                        if (!int.TryParse(datas[19], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "制热量有错误，该字段类型是 数字；";
                            allright = false;
                            //                            continue;

                        }
                    }
                }
                {//地下室层数

                    if (datas[20] != "")
                    {
                        int byear = -1;

                        if (!int.TryParse(datas[20], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "地下室层数有错误，该字段类型是 数字；";
                            allright = false;
                            //                            continue;

                        }
                    }
                }
                {//地下室面积

                    if (datas[22] != "")
                    {
                        int byear = -1;
                        if (!int.TryParse(datas[22], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "地下室面积有错误，该字段类型是 数字；";
                            allright = false;
                            //                            continue;

                        }
                    }
                }
                {//制冷量


                    if (datas[23] != "")
                    {
                        int byear = -1;
                        if (!int.TryParse(datas[23], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "制冷量有错误，该字段类型是 数字；";
                            allright = false;
                            //                            continue;                        
                        }
                    }
                }
                {//节能改造
                    if (datas[25] != "")
                    {
                        int byear = -1;
                        if (!int.TryParse(datas[25], out byear))
                        {
                            //将数据输出
                            //将数据输出
                            error += "节能改造有错误，该字段类型是 数字；";
                            allright = false;
                            //                            continue;                        
                        }
                    }
                }
            }
            else
            {
                error += "属性数目超出；";
            }
            if (error == "")
            {
                return true;
            }
            else
            {
                errorlines += "\n" + datastr + "," + error;
                return false;
            }
            #endregion
        }
        /// <summary>
        /// 备份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton16_Click(object sender, EventArgs e)
        {
            try
            {
                string processContent = "";
                string errormessage = "";
                WorkForm workform = new WorkForm();
                workform.Show(this);
                string fcname = Form1.建筑图层.Name;
                string folder1 = "c:\\";
                string filename1 = "aaa1.sde";
                if (System.IO.File.Exists(folder1 + filename1))
                {
                    System.IO.File.Delete(folder1 + filename1);
                }
                IWorkspaceFactory2 fac = ((IDataset)Form1.建筑图层.FeatureClass).Workspace.WorkspaceFactory as IWorkspaceFactory2;
                fac.Create(folder1, filename1, ((IDataset)Form1.建筑图层.FeatureClass).Workspace.ConnectionProperties, 0);
                Geoprocessor pro = new Geoprocessor();
                IWorkspaceFactory2 fac2 = new AccessWorkspaceFactoryClass() as IWorkspaceFactory2;
                //fac2.Create(
                string disk = "c:\\";
                string foldername = @"杭州建筑信息备份" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff") + ".mdb";
                CreatePersonalGDB cpg = new CreatePersonalGDB(disk, foldername);
                pro.Execute(cpg, null);
                foldername = "c:\\" + foldername;
                FeatureClassToFeatureClass f2f = new FeatureClassToFeatureClass(folder1 + filename1 + "\\" + fcname, foldername, fcname);
                workform.SetTitle("正在备份建筑数据");
                pro.Execute(f2f, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    string info = pro.GetMessage(i);
                    if (info.ToLower().Contains("error"))
                    {
                        errormessage += "\r\n备份建筑数据出错";
                    }
                    processContent += info + "\r\n";
                    workform.SetText(processContent);
                }
                processContent += "\r\n";
                fcname = Form1.街道图层.Name;
                f2f = new FeatureClassToFeatureClass(folder1 + filename1 + "\\" + fcname, foldername, fcname);
                workform.SetTitle("正在备份街道数据");
                pro.Execute(f2f, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    string info = pro.GetMessage(i);
                    if (info.ToLower().Contains("error"))
                    {
                        errormessage += "\r\n备份街道数据出错";
                    }
                    processContent += info + "\r\n";
                    workform.SetText(processContent);
                }
                processContent += "\r\n";
                fcname = Form1.用电建筑图层.Name;

                f2f = new FeatureClassToFeatureClass(folder1 + filename1 + "\\" + fcname, foldername, fcname);
                workform.SetTitle("正在备份用电建筑数据");
                pro.Execute(f2f, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    string info = pro.GetMessage(i);
                    if (info.ToLower().Contains("error"))
                    {
                        errormessage += "\r\n备份用电建筑数据出错";
                    }
                    processContent += info + "\r\n";
                    workform.SetText(processContent);
                }
                processContent += "\r\n";
                fcname = Form1.社区图层.Name;

                f2f = new FeatureClassToFeatureClass(folder1 + filename1 + "\\" + fcname, foldername, fcname);
                workform.SetTitle("正在备份社区数据");
                pro.Execute(f2f, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    string info = pro.GetMessage(i);
                    if (info.ToLower().Contains("error"))
                    {
                        errormessage += "\r\n备份社区数据出错";
                    }
                    processContent += info + "\r\n";
                    workform.SetText(processContent);
                }
                processContent += "\r\n";
                fcname = Settings.用电建筑信息;
                
                TableToTable t2t = new TableToTable(folder1 + filename1 + "\\" + fcname, foldername, fcname);
                workform.SetTitle("正在备份用电建筑信息数据");
                pro.Execute(t2t, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    string info = pro.GetMessage(i);
                    if (info.ToLower().Contains("error"))
                    {
                        errormessage += "\r\n备份用电建筑信息数据出错";
                    }
                    processContent += info + "\r\n";
                    workform.SetText(processContent);
                }
                processContent += "\r\n";
                workform.StopWork();
                MessageBox.Show("数据备份完成！" + errormessage);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }
        /// <summary>
        /// 恢复
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton17_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Filter = "mdb|*.mdb";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string filename = dialog.FileName;
                    Geoprocessor geop = new Geoprocessor();
                    string folder1 = "c:\\";
                    string filename1 = "aaa.sde";
                    if (System.IO.File.Exists(folder1 + filename1))
                    {
                        System.IO.File.Delete(folder1 + filename1);
                    }
                    IWorkspaceFactory fac = ((IDataset)Form1.建筑图层.FeatureClass).Workspace.WorkspaceFactory;
                    fac.Create(folder1, filename1, ((IDataset)Form1.建筑图层.FeatureClass).Workspace.ConnectionProperties, 0);
                    DeleteFeatures deletefeatures = new DeleteFeatures(folder1 + filename1 + "\\" + Form1.建筑图层.Name);
                    WorkForm workform = new WorkForm();
                    workform.Show(this);
                    string processContent = "";
                    string errormessage = "";
                    workform.SetTitle("正在恢复建筑数据");

                    geop.Execute(deletefeatures, null);

                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n删除建筑数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    Append append = new Append(filename + "\\" + Form1.建筑图层.Name, folder1 + filename1 + "\\" + Form1.建筑图层.Name);

                    geop.Execute(append, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n恢复建筑数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    deletefeatures = new DeleteFeatures(folder1 + filename1 + "\\" + Form1.街道图层.Name);
                    workform.SetTitle("正在恢复街道数据");
                    geop.Execute(deletefeatures, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n删除街道数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    append = new Append(filename + "\\" + Form1.街道图层.Name, folder1 + filename1 + "\\" + Form1.街道图层.Name);
                    geop.Execute(append, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n恢复街道数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    deletefeatures = new DeleteFeatures(folder1 + filename1 + "\\" + Form1.用电建筑图层.Name);
                    workform.SetTitle("正在恢复用电建筑数据");
                    geop.Execute(deletefeatures, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n删除用电建筑数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    append = new Append(filename + "\\" + Form1.用电建筑图层.Name, folder1 + filename1 + "\\" + Form1.用电建筑图层.Name);
                    geop.Execute(append, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n恢复用电建筑数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    deletefeatures = new DeleteFeatures(folder1 + filename1 + "\\" + Form1.社区图层.Name);
                    workform.SetTitle("正在恢复社区数据");
                    geop.Execute(deletefeatures, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n删除社区数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    append = new Append(filename + "\\" + Form1.社区图层.Name, folder1 + filename1 + "\\" + Form1.社区图层.Name);
                    geop.Execute(append, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n恢复社区数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    workform.SetTitle("正在恢复用电建筑信息数据");
                    DeleteRows deleterows = new DeleteRows(folder1 + filename1 + "\\用电建筑信息");
                    geop.Execute(deleterows, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n删除用电建筑信息数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    append = new Append(filename + "\\用电建筑信息", folder1 + filename1 + "\\用电建筑信息");
                    geop.Execute(append, null);
                    for (int i = 0; i < geop.MessageCount; i++)
                    {
                        string info = geop.GetMessage(i);
                        if (info.ToLower().Contains("error"))
                        {
                            errormessage += "\r\n恢复用电建筑信息数据出错";
                        }
                        processContent += info + "\r\n";
                        workform.SetText(processContent);
                    }
                    processContent += "\r\n";
                    workform.StopWork();
                    MessageBox.Show("数据恢复完成！" + errormessage);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("恢复失败，原因：" + ex.Message);
            }
        }
        /// <summary>
        /// 数据检查
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton18_Click(object sender1, EventArgs e1)
        {
            try
            {
                DbConnection dbconn =
                    CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName,
                                       ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                dbconn.Open();
                DbCommand dbcomm = dbconn.CreateCommand();
                string atablename = ConfigurationManager.AppSettings["用电建筑信息"];
                string jianzhutablename = ConfigurationManager.AppSettings["用电建筑信息"];
                string buildid = ConfigurationManager.AppSettings["用电建筑编号"];
                string jbuildid = ConfigurationManager.AppSettings["建筑编号"];
                string[] bds = buildid.Split('.');
                buildid = bds[bds.Length - 1];
                string sql1 = "update " + Settings.建筑图层 + " set hasdata = 1 where " + Settings.建筑编号 + " in (select " + Settings.用电建筑编号 + " from " + Settings.用电建筑信息 + ") and hasdata <> 1";
                dbcomm.CommandText = sql1;
                dbcomm.ExecuteNonQuery();
                sql1 = "update " + Settings.建筑图层 + " set " + Settings.用电建筑编号  + " = '' where " + Settings.用电建筑编号 + " is not null and " + Settings.用电建筑编号 + " not in (select " + Settings.用电建筑编号 + " from " + Settings.用电建筑信息 + ")";
                dbcomm.CommandText = sql1;
                dbcomm.ExecuteNonQuery();
                sql1 = "update " + Settings.建筑图层 + " set hasdata = 0 where BuildingID not in (select " + Settings.用电建筑编号 + " from " + Settings.用电建筑信息 + ") and hasdata <> 0";
                dbcomm.CommandText = sql1;
                dbcomm.ExecuteNonQuery();
                sql1 = "delete from " + Settings.用电建筑信息 + " where " + Settings.用电建筑编号 + " not in (select " + Settings.建筑编号 + " from " + Settings.建筑图层 + ")";
                dbcomm.CommandText = sql1;
                dbcomm.ExecuteNonQuery();
                sql1 = "delete from " + Settings.用电建筑图层 + " where " + Settings.用电建筑编号 + " not in (select " + Settings.用电建筑编号 + " from " + Settings.建筑图层 + ")";
                dbcomm.CommandText = sql1;
                dbcomm.ExecuteNonQuery();
                sql1 = "delete from " + Settings.用电建筑图层 + " where " + Settings.用电建筑编号 + " not in (select " + Settings.用电建筑编号 + " from " + Settings.用电建筑信息 + ")";
                dbcomm.CommandText = sql1;
                dbcomm.ExecuteNonQuery();
                string sql = ConfigurationManager.AppSettings["sql数据检查"];
                dbcomm.CommandText = sql;
                DbDataReader reader = dbcomm.ExecuteReader();
                QueryResultPanel form = QueryResultPanel.Instance;
                form.MapControl = axMapControl1.GetOcx() as IMapControl2;
                form.Clear();
                TreeView treeview = form.treeView1;
                TreeNode node = treeview.Nodes.Add("未合并建筑");
                int buildidindex = reader.GetOrdinal("buildingid");
                int envindex = reader.GetOrdinal("envelope");
                int typeindex = reader.GetOrdinal("shapetype");
                while (reader.Read())
                {
                    string tag = reader.GetString(buildidindex);
                    int shapetype = int.Parse(reader.GetValue(typeindex).ToString());
                    shapetype += 2000;
                    TreeNode tnode = node.Nodes.Add(tag);
                    IGeometry geom = PnGeometryUtility.GetGeometry(shapetype, reader.GetString(envindex));
                    ContextMenuStrip cm = new ContextMenuStrip();
                    addContextMenuStrip(geom, ref cm, axMapControl1.GetOcx() as IMapControl2);
                    tnode.ContextMenuStrip = cm;
                }
                node.Expand();
                form.Show();
                form.BringToFront();
                reader.Close();
                DbCommand comm = dbconn.CreateCommand();
                comm.CommandText = ConfigurationManager.AppSettings["sql数据合法性检查"];
                reader = comm.ExecuteReader();
                string filename = "";
                string errorfileDir = Application.StartupPath + "\\错误数据" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff");
                if (!Directory.Exists(errorfileDir))
                    Directory.CreateDirectory(errorfileDir);
                string errorlines = ConfigurationManager.AppSettings["数据字段序列"];
                bool checkok = false;
                while (reader.Read())
                {
                    string shequname = reader.GetString(0);
                    if (filename == "")
                    {
                        filename = shequname;
                    }
                    if (filename != shequname)
                    {

                        File.AppendAllText(errorfileDir + "\\" + filename + ".csv", errorlines, Encoding.Default);
                        errorlines = ConfigurationManager.AppSettings["数据字段序列"];
                        filename = shequname;
                    }
                    checkdata(reader.GetString(1), ref checkok, ref errorlines, ConfigurationManager.AppSettings["数据字段序列"].Split(',').Length);
                }
                if (filename != "")
                    File.AppendAllText(errorfileDir + "\\" + filename + ".csv", errorlines, Encoding.Default);
                if (!checkok)
                {
                    Process.Start("explorer", errorfileDir);
                }
                dbconn.Close();
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 增加菜单 图形闪烁，zoomto ，pan to
        /// </summary>
        /// <param name="geo"></param>
        /// <returns></returns>
        internal static void addContextMenuStrip(IGeometry geo, ref ContextMenuStrip cm, IMapControl2 axMapControl1)
        {
            if (cm == null)
                cm = new ContextMenuStrip();
            ToolStripItem moveItem = cm.Items.Add("移动至");
            ToolStripItem zoomItem = cm.Items.Add("缩放至");
            ToolStripItem flashItem = cm.Items.Add("闪烁");

            cm.Tag = geo;

            moveItem.Click += delegate(object sender, EventArgs e)
            {
                IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                double x1 = geom1.Envelope.XMin + geom1.Envelope.Width / 2;
                double y1 = geom1.Envelope.YMin + geom1.Envelope.Height / 2;
                IPoint op = new PointClass();
                op.X = x1;
                op.Y = y1;
                IEnvelope env1 = axMapControl1.Extent;
                env1.CenterAt(op);
                axMapControl1.Extent = env1;
            };

            zoomItem.Click += delegate(object sender, EventArgs e)
            {
                IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                IEnvelope env2 = geom1.Envelope;
                if (env2.Dimension == esriGeometryDimension.esriGeometry0Dimension)
                {
                    double x1 = geom1.Envelope.XMin + geom1.Envelope.Width / 2;
                    double y1 = geom1.Envelope.YMin + geom1.Envelope.Height / 2;
                    IPoint op = new PointClass();
                    op.X = x1;
                    op.Y = y1;
                    IEnvelope env1 = axMapControl1.Extent;
                    env1.CenterAt(op);
                    axMapControl1.Extent = env1;
                }
                else
                {
                    axMapControl1.Extent = env2;
                }
                axMapControl1.Refresh(esriViewDrawPhase.esriViewGeography, null, env2);
            };
            flashItem.Click += delegate(object sender, EventArgs e)
            {
                IGeometry geom1 = (sender as ToolStripItem).Owner.Tag as IGeometry;
                FlashUtility.FlashGeometry(geom1, axMapControl1);
            };
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ///填充下拉框
            int count = axMapControl1.LayerCount;
            IFeatureLayer jiedaolayer = null;
            IFeatureLayer shequlayer = null;
            for (int i = 0; i < count; i++)
            {
                ILayer layer = axMapControl1.get_Layer(i);
                if (layer.Name == ConfigurationManager.AppSettings["街道图层"])
                {
                    jiedaolayer = layer as IFeatureLayer;
                }
                else if (layer.Name == ConfigurationManager.AppSettings["社区图层"])
                {
                    shequlayer = layer as IFeatureLayer;
                }
            }
            if (jiedaolayer != null && shequlayer != null)
            {
                IFeatureClass fclass = jiedaolayer.FeatureClass;
                IGeoDataset geods = fclass as IGeoDataset;
                NameAndGeometry ne1 = new NameAndGeometry("全部街道", geods.Extent);
                jiedaoComboBox2.Items.Add(ne1);
                List<NameAndGeometry> allshequ = new List<NameAndGeometry>();
                jiedao2shequ.Add(ne1.ToString(), allshequ);

                //int 
                IQueryFilter qfilter = new QueryFilterClass();
                IFeatureCursor fcursor = jiedaolayer.Search(qfilter, true);
                IFeature feature = fcursor.NextFeature();
                string jiedaoname = ConfigurationManager.AppSettings["街道名称"];
                string shequname = ConfigurationManager.AppSettings["社区名称"];
                int jiedaonameindex = fclass.FindField(jiedaoname);
                int shequnameindex = shequlayer.FeatureClass.FindField(shequname);
                while (feature != null)
                {
                    string namevalue = feature.get_Value(jiedaonameindex).ToString();
                    IEnvelope env = feature.Extent;
                    NameAndGeometry ne = new NameAndGeometry(namevalue, feature.ShapeCopy);
                    jiedaoComboBox2.Items.Add(ne);
                    IQueryFilter2 filter2 = new QueryFilterClass() as IQueryFilter2;
                    filter2.WhereClause = jiedaoname + " = '" + namevalue + "'";
                    //ISpatialFilter sfilter = new SpatialFilterClass();
                    //sfilter.Geometry = feature.Shape;
                    //sfilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;
                    IFeatureCursor cursor1 = shequlayer.Search(filter2, true);
                    IFeature feature1 = cursor1.NextFeature();
                    List<NameAndGeometry> shequs = new List<NameAndGeometry>();
                    while (feature1 != null)
                    {
                        shequs.Add(new NameAndGeometry(feature1.get_Value(shequnameindex).ToString(), feature1.ShapeCopy));
                        feature1 = cursor1.NextFeature();
                    }
                    jiedao2shequ.Add(namevalue, shequs);
                    Marshal.ReleaseComObject(cursor1);
                    allshequ.AddRange(shequs);
                    feature = fcursor.NextFeature();
                }
                Marshal.ReleaseComObject(fcursor);
            }
        }
        public class NameAndGeometry
        {
            private IGeometry envelope;
            private string name;

            public NameAndGeometry(string name, IGeometry envelope)
            {
                this.name = name;
                this.envelope = envelope;
            }

            public IGeometry Geometry
            {
                get { return envelope; }
            }

            public override string ToString()
            {
                return name;
            }
        }

        private Hashtable jiedao2shequ = new Hashtable();

        private void jiedaoComboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (jiedaoComboBox2.SelectedItem == null)
                return;
            NameAndGeometry ne = jiedaoComboBox2.SelectedItem as NameAndGeometry;
            axMapControl1.Extent = ne.Geometry.Envelope;
            shequComboBox1.Items.Clear();
            shequComboBox1.Items.AddRange((jiedao2shequ[ne.ToString()] as List<NameAndGeometry>).ToArray());
        }

        private void shequComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (shequComboBox1.SelectedItem == null)
                return;
            NameAndGeometry ne = shequComboBox1.SelectedItem as NameAndGeometry;
            axMapControl1.Extent = ne.Geometry.Envelope;
        }

        private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                toolStripButton1_Click_1(null, null);
            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {

            ((IGeoFeatureLayer)建筑图层).DisplayAnnotation = !((IGeoFeatureLayer)建筑图层).DisplayAnnotation;
            toolStripButton5.Text = ((IGeoFeatureLayer)建筑图层).DisplayAnnotation ? "关闭标注" : "显示标注";
        }

        private void toolStripButton19_Click(object sender, EventArgs e)
        {
            数据导出 form = new 数据导出();
            form.InitTree(jiedao2shequ);
            form.ShowDialog(this);
        }

        private void toolStripButton20_Click(object sender, EventArgs e)
        {
            数据导入 form = new 数据导入();
            form.ShowDialog(this);
        }

        private void toolStripButton21_Click(object sender, EventArgs e)
        {
            if (单元数检查 != null)
                单元数检查.Visible = !单元数检查.Visible;
            if (单元数检查.Visible)
            {
                toolStripButton21.Text = "关闭单元数检查";
            }
            else
            {
                toolStripButton21.Text = "打开单元数检查";
            }
        }

        private void toolStripButton11_Click_1(object sender, EventArgs e)
        {
            if (道路 != null)
            {
                道路.Visible = !道路.Visible;
                if (道路.Visible)
                {
                    toolStripButton11.Text = "关闭道路";
                }
                else
                {
                    toolStripButton11.Text = "打开道路";
                }
            }
        }
    }
}
